package c.x.jy.service.utils.wechat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import c.x.jy.common.exception.RRException;
import c.x.jy.dao.entity.MemberEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;

//@Controller
//@RequestMapping("getWxInfo")
@Slf4j
public class WechatUtil {
	
//	@Autowired
	//private MemberUtil userUtil;
	
	//@Autowired
	//private MemberService memberService;// 客户
	
	//   protected static Logger logger = LoggerFactory.getLogger(WechatUtil.class);
	/**
	 * 获取服务号用户信息存入表中
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
 */
 
	public static  MemberEntity   getUserByCode( HttpServletRequest request, HttpServletResponse response,WechatConfig config) throws Exception{
		// 判断session user是否存在
		 MemberEntity memberEntity = null; 
		String uri = request.getRequestURI();



		//	String contextPath = request.getContextPath();
		// code 是否存在
		String code = request.getParameter("code");
		log.info("code:{}",code);
		if (StringUtils.isEmpty(code)) {
			// 获取原请求的url
			String serverName = request.getServerName();
 
			  String os = System.getProperty("os.name"); 
				 String url=null;
			  if(os.toLowerCase().startsWith("win")){ 
				  url = request.getScheme()+"://" + serverName +":"+request.getServerPort()+ request.getRequestURI() +  (request.getQueryString()==null?"":"?" +request.getQueryString());
			  }else
			   url = request.getScheme()+"://" + serverName  + request.getRequestURI() +  (request.getQueryString()==null?"":"?" +request.getQueryString());
 
			 log.info("url:{}",url);
			// 拼接url并转发
			response.sendRedirect(WechatAuthorizeUtils.getCodeBySnsapiUserInfo(url,config));

			return null;
		} else {
		//	String openid=WechatAuthorizeUtils.getUserOpenId(code, GetConfig.getAppId(), GetConfig.getAppSecret());
			try {
				memberEntity=	WechatAuthorizeUtils.getUserData1(code, config);	
			} catch (RRException e) {

				if(e.getMessage().equals("40163")||e.getMessage().equals("40029") ){
				  String query=	request.getQueryString();

				  if(query!=null&&query.indexOf("code=")!=-1) {
					  query=query.substring(0,query.indexOf("&code=") );
				  };
					String url = request.getScheme()+"://" + request.getServerName() +":"+request.getServerPort()+ request.getRequestURI() + "?" + query;
					response.sendRedirect(WechatAuthorizeUtils.getCodeBySnsapiUserInfo(url,config));
				}
				return null;
			}
			log.info("openid:{}",memberEntity);
		}

		return memberEntity;

	}
 
		
}
